﻿using System;
using System.Linq;
using System.Reflection;
using AspectCore.Extensions.DependencyInjection;
using HystrixCoreDemo.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace HystrixCoreDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        private void RegisterHystriCommandService(Assembly assembly, IServiceCollection services)
        {
            foreach (var currentType in assembly.GetExportedTypes())
            {
                var isHystrixCommand = currentType.GetMethods().Any(x => x.GetCustomAttribute(typeof(HystrixCommandAttribute)) != null);

                if (isHystrixCommand)
                {
                    services.AddSingleton(currentType);
                }
            }
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //services.AddSingleton<Person>();
            this.RegisterHystriCommandService(this.GetType().Assembly, services);

            return services.BuildAspectCoreServiceProvider();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
